package com.likan.chqjtgc;

import com.likan.chqjtgc.commons.AuthLoginClientConfig;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;

/**
 * @author  liuxinghong
 * 配值fegin在模块间调用时，请求头携带token的配置
 */
@Configuration
public class FeignOauth2RequestInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        SecurityContext securityContext = SecurityContextHolder.getContext();
        Authentication authentication = securityContext.getAuthentication();
        if (authentication != null && authentication.getDetails() instanceof OAuth2AuthenticationDetails) {
            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) authentication.getDetails();
            requestTemplate.header(AuthLoginClientConfig.AUTHORIZATION_HEADER, String.format("%s %s", AuthLoginClientConfig.BEARER_TOKEN_TYPE, details.getTokenValue()));
        }

    }

}